
import 'package:dali_ng_pera/global/dnp_global_manager.dart';
import 'package:dali_ng_pera/manager/dnp_cache_manager.dart';
import '../manager/dnp_plugin_manager.dart';

class DnpNetConfig {

  static final DnpNetConfig _shared = DnpNetConfig._internal();
  factory DnpNetConfig() => _shared;
  DnpNetConfig._internal();

  Map<String, String> infoParameters = {};

  String globalDomain = "http://47.84.62.48/repeatedeye";

  Future<void> initialize() async {
    await _loadPublicParameters();
  }

  String globalPath(String path) {
    return globalDomain + concatenateUrl(path);
  }

  _loadPublicParameters() async {
    String? holiday = await DnpPluginManager().plugin.holiday;
    String? bridehead = await DnpPluginManager().plugin.cannot;
    String? footed = await DnpPluginManager().plugin.footed;
    String? eyed = await DnpPluginManager().plugin.considerably;
    String? fearlessness = await DnpPluginManager().plugin.fearlessness;

    infoParameters = {
      "holiday": holiday ?? "",
      "bridehead": bridehead ?? "",
      "footed": footed ?? "",
      "eyed": eyed ?? "",
      "fearlessness": fearlessness ?? ""
    };

    String knowledge = DnpGlobalManager().knowledge;

    if (knowledge.isNotEmpty) {
      infoParameters["knowledge"] = knowledge;
    }
  }

  void saveKnowledge(String? text) {
    if (text == null) {return;}
    DnpCacheManager().saveString("KDnpKnowledge", text);
    infoParameters["knowledge"] = text;
  }

  void saveLoudness(int? text) {
    if (text == null) return;
    infoParameters['loudness'] = text.toString();
  }

  String concatenateUrl(String text) {
    final resultParams = _dealWithParams(infoParameters);
    return resultParams.isEmpty ? text : _dealWithPathAndParams(text, resultParams);
  }

  String _dealWithParams(Map<String, String> params) {
    return params.entries
        .map((e) => '${e.key}=${Uri.encodeQueryComponent(e.value)}')
        .join('&');
  }

  String _dealWithPathAndParams(String text, String params) {
    return text.contains('?') ? '$text&$params' : '$text?$params';
  }

}